﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TableProto;
using WCBG.ToolsForUnity.Extension;
using WCBG.ToolsForUnity.Tools;

public class DrawLetterWindow : BaseDrawWindow<DrawLetterWindow>
{

    #region ui property

    //public Transform _LawnPanel { get; set; }
    //public Transform _SnowPanel { get; set; }
    //public Transform _SeaPanel { get; set; }
    //public Transform _PaddyfieldPanel { get; set; }

    public Transform _Lawn_Brush { get; set; }
    public Transform _Snow_Brush { get; set; }
    public Transform _Sea_Brush { get; set; }
    public Transform _Paddyfield_Brush { get; set; }
    public Transform _Letter_Parent { get; set; }

    public Button _Btn_Return { get; set; }
    public Image _Mask { get; set; }
    public Image _Sign { get; set; }
    //public Image _EffectMask { get; set; }
    public Transform _AnimParent { get; set; }
    public Transform _EffectPoint { get; set; }
    //public Transform _LetterEffect { get; set; }
    //public Image _EffectTest { get; set; }


    #endregion


    private System.Action<bool> completeCallback;
    //private System.Action eatAnimCallback;

    private const string letterBasePath = StudyPath.math_drawletterBasePath;

    private EnglishLetterInfo info;
    private GameObject m_LoadLetter;    // 加载的字母资源
    private GameObject m_letterEffect;  // 撒字母的特效
    private EEnglishSceneType m_sceneType;




    protected override void OnClose()
    {

        StopBrushAudio();
        completeCallback = null;
        DrawRealize2D.DestroyInstance();
        GameObject.Destroy(m_LoadLetter);
        for (int i = 0; i < _AnimParent.childCount; i++)
        {
            GameObject.Destroy(_AnimParent.GetChild(i).gameObject);
        }

        if (m_LoadLetter != null)
        {
            GameObject.Destroy(m_LoadLetter);
            m_LoadLetter = null;
        }
        if (m_letterEffect != null)
        {
            GameObject.Destroy(m_letterEffect);
            m_letterEffect = null;
        }
    }

    protected override void AddListeners()
    {
        _Btn_Return.onClick.AddListener(OnButtonReturnClick);
        //_EffectMask.gameObject.AddComponentEx<UIInputHandler>().OnDown += OnEffectMaskDown;
        EventBus.Instance.AddEventHandler(EventID.ON_MOUSE_BUTTON_DOWN, OnMouseDown);
        EventBus.Instance.AddEventHandler(EventID.ON_MOUSE_BUTTON_UP, OnMouseUp);
        _Lawn_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnDown += OnBrushDown;
        _Snow_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnDown += OnBrushDown;
        _Sea_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnDown += OnBrushDown;
        _Paddyfield_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnDown += OnBrushDown;

        _Lawn_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnEnter += OnBrushEnter;
        _Snow_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnEnter += OnBrushEnter;
        _Sea_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnEnter += OnBrushEnter;
        _Paddyfield_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnEnter += OnBrushEnter;

        _Lawn_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnExit += OnBrushExit;
        _Snow_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnExit += OnBrushExit;
        _Sea_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnExit += OnBrushExit;
        _Paddyfield_Brush.Find("BrushImage").AddComponentEx<UIInputHandler>().OnExit += OnBrushExit;
    }

    protected override void RemoveListensers()
    {
        _Btn_Return.onClick.RemoveAllListeners();
        EventBus.Instance.RemoveEventHandler(EventID.ON_MOUSE_BUTTON_DOWN, OnMouseDown);
        EventBus.Instance.RemoveEventHandler(EventID.ON_MOUSE_BUTTON_UP, OnMouseUp);
        _Lawn_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnDown -= OnBrushDown;
        _Snow_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnDown -= OnBrushDown;
        _Sea_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnDown -= OnBrushDown;
        _Paddyfield_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnDown -= OnBrushDown;

        _Lawn_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnEnter -= OnBrushEnter;
        _Snow_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnEnter -= OnBrushEnter;
        _Sea_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnEnter -= OnBrushEnter;
        _Paddyfield_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnEnter -= OnBrushEnter;

        _Lawn_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnExit -= OnBrushExit;
        _Snow_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnExit -= OnBrushExit;
        _Sea_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnExit -= OnBrushExit;
        _Paddyfield_Brush.Find("BrushImage").GetComponent<UIInputHandler>().OnExit -= OnBrushExit;
    }



    protected override void PlayBrushAudio()
    {
        if (m_audio == null)
        {
            switch (m_sceneType)
            {
                case EEnglishSceneType.Lawn:
                case EEnglishSceneType.Paddyfield:
                    m_audio = this.PlayAudioEx(StudyAudioName.t_31006, true);
                    break;
                case EEnglishSceneType.Sea:
                case EEnglishSceneType.Snow:
                    m_audio = this.PlayAudioEx(StudyAudioName.t_31012, true);
                    break;
            }
        }
    }




    public void StartDrawLetter(EnglishLetterInfo info, bool bIsLower, EEnglishSceneType type, System.Action<bool> onDrawCompleteCallback = null)
    {
        m_sceneType = type;
        this.info = info;

        if (m_LoadLetter != null)
        {
            GameObject.Destroy(m_LoadLetter);
            m_LoadLetter = null;
        }

        m_LoadLetter = LoadLetter(info.name, bIsLower);
        if (m_LoadLetter == null)
        {
            bIsDrawing = false;
            //if (callback != null)
            //{
            //    callback(false);
            //}
            return;
        }
        Transform brush = null;
        switch (type)
        {
            case EEnglishSceneType.Lawn:

                brush = _Lawn_Brush.transform;
                break;
            case EEnglishSceneType.Paddyfield:

                brush = _Paddyfield_Brush.transform;
                break;
            case EEnglishSceneType.Sea:

                brush = _Sea_Brush.transform;
                break;
            case EEnglishSceneType.Snow:

                brush = _Snow_Brush.transform;
                break;
        }

        completeCallback = onDrawCompleteCallback;
        bIsDrawing = true;
        isBrushPlaying = true;
        m_spriteSeqArray = brush.GetComponentsInChildren<SpriteSequenceFrame>(true);
        StopBrushAnimation();
        SetScenePanelActive(type);

        DrawRealize2D.Instance.DrawNumber(m_LoadLetter.transform, brush, _Mask.transform, _Sign, WindowManager.Instance.canvas, _AnimParent, OnDrawComplete, OnEatAnim);
    }

    private void OnEatAnim()
    {
        string[] arr = info.letter_draw_audio.Split(';');
        if (arr.Length == 2)
        {
            this.PlayCommonAudioEx(arr[0].Trim());
        }
        else
        {
            this.PlayEnglishAudioEx(info.letter_draw_audio);
        }
    }

    private void OnDrawComplete()
    {
        PlayLetterEffect(info.name, info.bigorsmall == 1);
        EnglishLediAnimationWindow.Instance.PlayLediTalkAnimation(EnglishLediAnimationWindow.ELediFadeInType.BottomLeft, info.ledi_letter_audio, () =>
        {
            if (completeCallback != null)
            {
                completeCallback(true);
            }
        });
    }

    public void PlayLetterEffect(string letter, bool isBigLetter)
    {
        string spriteName = isBigLetter ? letter + "(big)" : letter.ToLower() + "(small)";
        Sprite sprite = Res.LoadSprite(StudyPath.english_bigandsmall_letter_basepath + spriteName);
        if (sprite == null)
        {
            Debug.LogError("Load sprite error: spriteName:" + spriteName);
            return;
        }
        Texture2D texture = sprite.ConvertToTexture2D();

        m_letterEffect = this.PlayEffectEx(StudyPath.effect_502003021, _EffectPoint, 5, FTools.CreateSquareTexture(texture), EGameLayerMask.UI);
    }



    private GameObject LoadLetter(string name, bool bIsLower)
    {
        string path = "";
        if (bIsLower)
            path = letterBasePath + "SmallLetter_" + name.ToLower();
        else
            path = letterBasePath + "Letter_" + name;

        GameObject go = Res.LoadObj(path);
        if (go == null)
        {
            return null;
        }
        go.transform.SetParent(_Letter_Parent.transform);
        RectTransform rect = go.transform as RectTransform;
        rect.anchoredPosition3D = Vector3.zero;
        rect.sizeDelta = Vector2.zero;
        rect.localScale = Vector3.one;
        rect.localRotation = Quaternion.identity;

        return go;
    }

    private void SetScenePanelActive(EEnglishSceneType type)
    {
        //_LawnPanel.gameObject.SetActive(false);
        //_PaddyfieldPanel.gameObject.SetActive(false);
        //_SeaPanel.gameObject.SetActive(false);
        //_SnowPanel.gameObject.SetActive(false);

        _Lawn_Brush.gameObject.SetActive(false);
        _Paddyfield_Brush.gameObject.SetActive(false);
        _Sea_Brush.gameObject.SetActive(false);
        _Snow_Brush.gameObject.SetActive(false);

        //switch (type)
        //{
        //    case EEnglishSceneType.Lawn:

        //        _LawnPanel.gameObject.SetActive(true);
        //        break;
        //    case EEnglishSceneType.Paddyfield:

        //        _PaddyfieldPanel.gameObject.SetActive(true);
        //        break;
        //    case EEnglishSceneType.Sea:

        //        _SeaPanel.gameObject.SetActive(true);
        //        break;
        //    case EEnglishSceneType.Snow:

        //        _SnowPanel.gameObject.SetActive(true);
        //        break;
        //}
    }




    #region uievent

    private void OnButtonReturnClick()
    {
        //Debug.LogError ("退出游戏");
        
        DrawRealize2D.DestroyInstance();
        if (completeCallback != null)
        {
            completeCallback(false);
            completeCallback = null;
        }
        GameObject.Destroy(m_LoadLetter);

    }

    protected void OnMouseDown()
    {
        //if (EnglishLediAnimationWindow.Instance._Mask.gameObject.activeSelf)
        //    return;

        //if (WindowManager.Instance.eventSystem.IsPointerOverGameObject())
        //    return;

        ////Transform target = FTools.GetRaycastHitTarget(WindowManager.Instance.camera, Input.mousePosition, 99999);
        ////if (target != null && target.name == "MaskCollider")
        ////{
        ////    return;
        ////}

        //Vector3 hitPoint = Vector3.zero;
        //if (FTools.GetRaycastHitPoint(WindowManager.Instance.camera, Input.mousePosition, 99999, out hitPoint))
        //{
        //    string spriteName = info.bigorsmall == 1 ? info.name + "(big)" : info.name.ToLower() + "(small)";
        //    Sprite sprite = UISpriteManager.Instance.GetSprite(emUIAltas.English_BigAndSmallLetter, spriteName);
        //    if (sprite != null)
        //    {
        //        Texture2D texture = sprite.ConvertToTexture2D();
        //        GameObject effect = this.PlayEffectEx(StudyPath.effect_502003021, hitPoint, 5, FTools.CreateSquareTexture(texture), EGameLayerMask.UI);
        //        effect.transform.SetParent(_EffectPoint);
        //        effect.transform.localRotation = Quaternion.identity;
        //    }
        //}
    }

    #endregion


}
